/*
 * MapTile.cpp
 *
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses 
 */

#include "MapTile.h"
#include <algorithm>

MapTile::MapTile() {
    object = 0;
    dropedObject = 0;
}

bool MapTile::insertObject(MapObject* object) {
    // Nothing in the tile
    if ((this->object == 0) && (dropedObject == 0)) {
        this->object = object;
        return true;
    }
    // There's an object, collision is resolved
    if ((this->object != 0) && (! object->collideWith(this->object))) {
        return false;
    }
    // Object in tile didn't stop the moving one, if there's still one and is destroyed
    if ((this->object != 0) && (this->object->isDestroyed())) {
        this->object = 0;
    }
    // There's a dropped object, collision is resolved
    if ((dropedObject != 0) && (! object->collideWith(this->dropedObject))) {
        return false;
    }
    if (object->isDestroyed()) {
        this->object = 0;
    } else {
        this->object = object;
    }
    return true;
}

bool MapTile::dropObject(MapObject* object) {
    if (dropedObject != 0) {
        return false;
    }
    dropedObject = object;
    return true;
}

MapObject* MapTile::getObject() {
    return object;
}

MapObject* MapTile::getDropedObject() {
    return dropedObject;
}

MapObject* MapTile::removeObject() {
    MapObject* ret_object = object;
    object = 0;
    return ret_object;
}

bool MapTile::objectDropedOn() {
    return dropedObject != 0;
}

MapObject* MapTile::removeDropedObject() {
    MapObject* ret_object = 0;
    if (objectDropedOn()) {
        ret_object = dropedObject;
        dropedObject = 0;
    }
    return ret_object;
}

void MapTile::applyEffect(MapEffect* effect) {
    if (object != 0) {
        effect->applyTo(object);
        if (object->isDestroyed()) {
            object = 0;
        }
    }
}

bool MapTile::isOccupied() {
    return object != 0;
}

MapTile::~MapTile() {

}
